package com.wenyu.wenyuyuedu.activity;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.view.Window;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.wenyu.wenyuyuedu.R;
import com.wenyu.wenyuyuedu.bean.WXLoginBea;
import com.wenyu.wenyuyuedu.bean.homepager.LoginBean;
import com.wenyu.wenyuyuedu.global.ApiWrapper;
import com.wenyu.wenyuyuedu.server.homepager.Homepage_All_Server;
import com.wenyu.wenyuyuedu.utils.AbSharedUtil;
import com.wenyu.wenyuyuedu.utils.MyToast;
import com.wenyu.wenyuyuedu.utils.SharedConstants;

import java.util.HashMap;

import butterknife.ButterKnife;
import butterknife.InjectView;
import cn.sharesdk.framework.Platform;
import cn.sharesdk.framework.PlatformActionListener;
import cn.sharesdk.framework.PlatformDb;
import cn.sharesdk.framework.ShareSDK;
import cn.sharesdk.wechat.friends.Wechat;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/*
* 登陆
* */
public class LoginActivity extends AppCompatActivity implements View.OnClickListener {

    @InjectView(R.id.tv_enter)
    TextView tvEnter;
    @InjectView(R.id.btn_wx_login)
    TextView btnWxLogin;
    @InjectView(R.id.tv_login_agreement)
    TextView tvLoginAgreement;
    private Intent intent;
    /*quickLogin  代表登陆方式是三方登陆*/
    private String loginType = "quickLogin";
    /*type代表类型  4代表微信*/
    private int type = 4;
    private Platform wechat;
    private String nickname;
    private String icon;
    private String openid;
    private String token_key;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        ButterKnife.inject(this);
        initControl();
        String token = AbSharedUtil.getString(LoginActivity.this, SharedConstants.USER_TOKEN);
        if (token == "") {
        } else if (token == null) {
        } else {
            intent.setClass(getApplicationContext(), MainActivity.class);
            startActivity(intent);
            this.finish();
        }

    }

    private void initControl() {
        intent = new Intent();
        btnWxLogin.setOnClickListener(this);
        tvEnter.setOnClickListener(this);
        tvLoginAgreement.setOnClickListener(this);
    }

    AlertDialog ad;
    private TextView quxiao;
    private TextView queding;

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            //微信登陆
            case R.id.btn_wx_login:

                    wechat = ShareSDK.getPlatform(Wechat.NAME);
                    initThirdLoginAtWechat(wechat);

                break;
            //直接进入
            case R.id.tv_enter:
                intent.setClass(LoginActivity.this, MainActivity.class);
                startActivity(intent);
                AbSharedUtil.putString(LoginActivity.this, SharedConstants.DENGLU, 1 + "");
            //    AbSharedUtil.putString(LoginActivity.this, SharedConstants.USER_TOKEN, "68de68c294dff19e0397f2d8311fd0d7");
                // AbSharedUtil.putString(LoginActivity.this, SharedConstants.USER_TOKEN, "");
                finish();
                break;
            /*用户协议*/
            case R.id.tv_login_agreement:
                intent.setClass(LoginActivity.this,UserAgreementActivity.class);
                startActivity(intent);
                break;
        }
    }

    /*登陆*/
    private void request() {
   /*     final ProgressDialog progressDialog = new ProgressDialog(this);
        progressDialog.setMessage("登陆中。。。");
        progressDialog.show();*/
        Homepage_All_Server homepage_all_server = ApiWrapper.getInstance().create(Homepage_All_Server.class);
        Call<LoginBean> login = homepage_all_server.getLogin(loginType, openid, token_key, nickname, type, icon);
        login.enqueue(new Callback<LoginBean>() {
            @Override
            public void onResponse(Call<LoginBean> call, Response<LoginBean> response) {
                LoginBean body = response.body();
                if (body != null) {
                    int code = body.getCode();
                    if (code == 1) {
                        String token = body.getToken();
                        AbSharedUtil.putString(LoginActivity.this, SharedConstants.USER_TOKEN, token);
                        System.out.println("LoginActivity: 当前的token" + token);
                        AbSharedUtil.putString(LoginActivity.this, SharedConstants.USER_NICKNAME, nickname);
                        AbSharedUtil.putString(LoginActivity.this, SharedConstants.USER_ICON, icon);
                        AbSharedUtil.putString(LoginActivity.this, SharedConstants.DENGLU, 1 + "");
                        MyToast.showToast(LoginActivity.this, "登陆成功", Toast.LENGTH_SHORT);
                        intent.setClass(LoginActivity.this, MainActivity.class);
                        startActivity(intent);
                        Platform platform = ShareSDK.getPlatform(Wechat.NAME);
                        platform.removeAccount(true);
                        finish();
                        //progressDialog.dismiss();
                    } else if (code == 1401) {
                        Platform platform = ShareSDK.getPlatform(Wechat.NAME);
                        platform.removeAccount(true);
                        MyToast.showToast(LoginActivity.this, "用户名不能为空", Toast.LENGTH_SHORT);
                        //  progressDialog.dismiss();
                    } else if (code == 1402) {
                        Platform platform = ShareSDK.getPlatform(Wechat.NAME);
                        platform.removeAccount(true);
                        MyToast.showToast(LoginActivity.this, "密码不能为空", Toast.LENGTH_SHORT);
                        //progressDialog.dismiss();
                    } else if (code == 1403) {
                        Platform platform = ShareSDK.getPlatform(Wechat.NAME);
                        platform.removeAccount(true);
                        MyToast.showToast(LoginActivity.this, "用户不存在或被禁用", Toast.LENGTH_SHORT);
                        // progressDialog.dismiss();
                    } else if (code == 1404) {
                        Platform platform = ShareSDK.getPlatform(Wechat.NAME);
                        platform.removeAccount(true);
                        MyToast.showToast(LoginActivity.this, "密码错误", Toast.LENGTH_SHORT);
                        //progressDialog.dismiss();
                    }
                }
            }

            @Override
            public void onFailure(Call<LoginBean> call, Throwable t) {
                Platform platform = ShareSDK.getPlatform(Wechat.NAME);
                platform.removeAccount(true);
                MyToast.showToast(LoginActivity.this, "网络异常，请稍后重试", Toast.LENGTH_SHORT);
                // progressDialog.dismiss();
            }
        });
        ad.dismiss();
    }

    //微信第三方登陆
    public void initThirdLoginAtWechat(Platform wechat) {
        //回调信息，可以在这里获取基本的授权返回的信息，但是注意如果做提示和UI操作要传到主线程handler里去执行
        wechat.setPlatformActionListener(new PlatformActionListener() {

            @Override
            public void onError(Platform arg0, int arg1, Throwable arg2) {
                // TODO Auto-generated method stub
                arg2.printStackTrace();
            }

            @Override
            public void onComplete(Platform arg0, int arg1, HashMap<String, Object> arg2) {
                // TODO Auto-generated method stub
                //输出所有授权信息
                PlatformDb db = arg0.getDb();
                String s = db.exportData();
                Gson gson = new Gson();
                WXLoginBea wxLoginBea = gson.fromJson(s, WXLoginBea.class);
                nickname = wxLoginBea.getNickname();
                icon = wxLoginBea.getIcon();
                openid = wxLoginBea.getOpenid();
                token_key = wxLoginBea.getToken();
                request();
            }

            @Override
            public void onCancel(Platform arg0, int arg1) {
                // TODO Auto-generated method stub

            }
        });
        //authorize与showUser单独调用一个即可
        // wechat.authorize();//单独授权,OnComplete返回的hashmap是空的
        if (wechat.isAuthValid()) {
            // Toast.makeText(this, "123456", Toast.LENGTH_LONG).show();
        }
        wechat.showUser(null);//授权并获取用户信息

        //移除授权
        //weibo.removeAccount(true);
    }

    //执行授权,获取用户信息
    private void authorize(Platform plat) {
        if (plat == null) {
            popupOthers();
            return;
        }

        plat.setPlatformActionListener((PlatformActionListener) this);
        //关闭SSO授权
        plat.SSOSetting(true);
        plat.showUser(null);
    }

    //其他登录对话框
    private void popupOthers() {
        Dialog dlg = new Dialog(LoginActivity.this, R.style.WhiteDialog);
        View dlgView = View.inflate(LoginActivity.this, R.layout.tpl_other_plat_dialog, null);
        View tvFacebook = dlgView.findViewById(R.id.tvFacebook);
        tvFacebook.setTag(dlg);
        tvFacebook.setOnClickListener(this);
        View tvTwitter = dlgView.findViewById(R.id.tvTwitter);
        tvTwitter.setTag(dlg);
        tvTwitter.setOnClickListener(this);

        dlg.requestWindowFeature(Window.FEATURE_NO_TITLE);
        dlg.setContentView(dlgView);
        dlg.show();
    }

}
